<template>
  <div id="invReaStDiv">
    <Breadcrumb content="低储查询" />
    <div class="bodyContent">
      <vxe-form :data="searchForm" class="searchform form-input-m">
        <vxe-form-item title="仓库">
          <el-select v-model="searchForm.storeCode" placeholder="请选择仓库" ref="selectOrgRef" style="width:180px;" clearable @clear="clearStoreCode">
            <el-option hidden :value="searchForm.storeCode ? searchForm.storeCode : ''" :label="searchForm.storeName"></el-option>
            <el-tree filterable :data="invStoreList" :props="defaultProps" :expand-on-click-node="false" :default-expand-all="true" @node-click="handleTypeNodeClick" highlight-current ref="orgTreeRef" node-key="storeCode" class="tools-tree"></el-tree>
          </el-select>
        </vxe-form-item>
        <vxe-form-item title="商品">
          <VxePulldownSelectionWithNa style="width: 100%" :url="'/lis/inv/invReagent/findInvReagentList'" @confirmClick="SelectRowClick" :tableColumn="[
                          { type: 'seq', title: '#', width: '30px' },
                          { field: 'reaNo', title: '名称' },
                          { field: 'reaNa', title: '编码' }
                        ]" :aimKeys="[
                          { aimKey: 'reaNo', rowKey: 'reaNo' },
                          { aimKey: 'reaNa', rowKey: 'reaNa' }
                        ]" :displayTexts="['reaNa']" :displayTextObj="searchForm.reaNo ? searchForm.reaNa : ''" />
        </vxe-form-item>
        <vxe-form-item>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-search" content="查询" :loading="tloading" @click="findReagentStockList"></vxe-button>
        </vxe-form-item>
      </vxe-form>
      <div class="tableBox">
        <div style="height: 400px; width: 1000px; margin: 0 auto" id="main"></div>

        <vxe-table ref="invReagentTableRef" :data="reagentStocList" :loading="tloading" :span-method="mergeRowMethod" class="mytable-scrollbar" border align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :header-cell-style="headerCellStyle" resizable show-overflow keep-source>
          <vxe-column type="checkbox" width="30"></vxe-column>
          <vxe-column field="reaNo" title="商品编号" >
          </vxe-column>
          <vxe-column field="reaNa" title="商品名称" >
          </vxe-column>
          <vxe-column field="storeName" title="仓库" >
          </vxe-column>
          <vxe-column field="specModel" title="规格型号" > </vxe-column>
          <vxe-column field="categorizeName" title="商品分类" > </vxe-column>
          <vxe-column field="unit" title="单位" > </vxe-column>
          <vxe-column field="quantity" title="在库数量" ></vxe-column>
          <vxe-column field="miniStock" title="最小库存量"></vxe-column>
          <vxe-column field="overrunNum" title="超限数量" ></vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import { AppStore } from '@/stores/store';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';
import * as echarts from "echarts";

// 全局变量定义区 ==========
let store = AppStore();
let searchForm = reactive({
  storeCode: (!isEmpty(store.curInvStoreObj) && !isEmpty(store.curInvStoreObj.storeCode))?store.curInvStoreObj.storeCode:'',
  storeName: (!isEmpty(store.curInvStoreObj) && !isEmpty(store.curInvStoreObj.storeName))?store.curInvStoreObj.storeName:'',
  reaNo: '',
  reaNa: '',
  manufacturerNo: ''
});

let defaultProps = {
  children: 'children',
  label: 'storeName'
};
let tloading = ref(false); //刷新加载状态
let reagentStocList: any = reactive([]);
let invStoreList: any = reactive([]);

// 方法定义区 =============
// 页面加载时更新组织机构列表(左侧)
onMounted(() => {
  findStoreManageTree();
  findReagentStockList();
  // 本地缓存中的报告单元
  //let localWorkGroupIngo = store.locWorkGroup;
});
/**设置表头单元格样式 */
function headerCellStyle({ column }) {
  if (column.field === 'overrunNum') {
    return {
      color: '#f80707' // 表头字体颜色
    };
  }
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findReagentStockList();
  }
}
function findReagentStockList() {
  tloading.value = true;
  reagentStocList.length = 0; //放入数据前清空数据
  const url = '/inv/invReagentStock/findLowStorageList';
  proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: {
          storeCode: searchForm.storeCode,
          reaNo: searchForm.reaNo,
          manufacturerNo: searchForm.manufacturerNo
        }
      })
      .then((res: any) => {
        reagentStocList.push(...res.data);
        const groupsData = [];
        let product = ['product', '在库数量', '最小库存量', '超限数量'];
        groupsData.push(product);
        reagentStocList.forEach((group: any) => {
          let dateData = [];
          dateData.push(group.reaNa);
          dateData.push(group.quantity);
          dateData.push(group.miniStock);
          dateData.push(group.overrunNum);
          groupsData.push(dateData);
        });
        initChart(groupsData);
        tloading.value = false;
      })
      .catch((err: any) => {
        tloading.value = false;
        // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
      });
}
function initChart(data) {
  var app = {};

  var chartDom = document.getElementById('main');
  var myChart = echarts.init(chartDom);
  var option;

  option = {
    legend: {},
    tooltip: {},
    dataset: {
      source: data
    },
    xAxis: { type: 'category' },
    yAxis: {},
    series: [{ type: 'bar' }, { type: 'bar' }, { type: 'bar' }]
  };

  option && myChart.setOption(option);
}
function findStoreManageTree() {
  invStoreList.length = 0;
  const url = '/inv/storeManage/findStoreManageTree';
  proxy.$http
      .get(url)
      .then((res: any) => {
        if (res.status.code !== 1) {
          proxy.$alert(res.status.msg, '提示');
        } else {
          invStoreList.push(...res.data.invStoreTree);
          if (!isEmpty(searchForm.storeCode)){
            setCurOrgTreeNode(searchForm.storeCode);
          }
        }
      })
      .catch((err: any) => {
        VxeMessage('获取机构失败', VxeNotifyType.error);
      });
}

function handleTypeNodeClick(data: any) {
  searchForm.storeCode = data.storeCode;
  searchForm.storeName = data.storeName;
  const selectOrgRef: any = proxy.$refs['selectOrgRef'];
  selectOrgRef.blur();
  findReagentStockList();
}

function clearStoreCode() {
  findReagentStockList();
}

function SelectRowClick(e) {
  e.aimKeys.forEach((r) => {
    searchForm[r.aimKey] = e.row[r.rowKey];
  });
  findReagentStockList();
}

function mergeRowMethod({ row, _rowIndex, column, visibleData }) {
  const fields = ['reaNo', 'reaNa'];
  const cellValue = row[column.field];
  if (cellValue && fields.includes(column.field)) {
    const prevRow = visibleData[_rowIndex - 1];
    let nextRow = visibleData[_rowIndex + 1];
    if (prevRow && prevRow[column.field] === cellValue) {
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (nextRow && nextRow[column.field] === cellValue) {
        nextRow = visibleData[++countRowspan + _rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  }
}

// 光标定位在指定字典分类上
function setCurOrgTreeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'orgTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}
</script>

<style lang="scss" scoped>
#invReaStDiv {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }
    .button-red {
      margin: 5px 0 5px 5px;
    }
    .searchform {
      padding: 10px 0 0 10px;

      :deep(.vxe-form--item) {
        margin-right: 30px;
      }
    }

    .searchform .vxe-input {
      --el-input-width: 120px;
    }

    .searchform .vxe-select {
      --el-select-width: 120px;
    }

    .tableBox {
      height: calc(100% - 40px);
      background-color: $base-white;
    }

    .el-tabs {
      height: 100%;
      // 右侧保存按钮
      .saveBtn {
        margin: 0px 30px;
      }
    }
  }
}
</style>
